//对外提供接口（controller）
package com.glxy.wxtakeaway.controller;

import com.alibaba.fastjson.JSONObject;
import com.glxy.wxtakeaway.entity.UserInfo;
import com.glxy.wxtakeaway.entity.Users;
import com.glxy.wxtakeaway.mapper.UsersMapper;
import com.glxy.wxtakeaway.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

//表示这个接口所有的方法查询出来的数据被渲染成json，返回到前端
@RestController
//接口路径
@RequestMapping("/users")
public class UsersController {

    //引入UserMapper接口
    @Resource
    UsersMapper usersMapper;

    //写入appid以及secret
    @Value("${wx.appid}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;

    private final RestTemplate restTemplate = new RestTemplate();
    //注册一个新用户（注册登录一体化）
    @PostMapping("/register")
    public Result<Object> registerUser(@RequestBody UserInfo userInfo){
        // 创建结果对象
        Result<Object> result = new Result<>();

        try {
            //获取code，头像，昵称
            String code=userInfo.getCode();
            String avatarUrl=userInfo.getAvatarUrl();
            String nickName=userInfo.getNickName();

//            解码头像和昵称
            String newAvatarUrl = URLDecoder.decode(avatarUrl,StandardCharsets.UTF_8.toString());
            String newNickName = URLDecoder.decode(nickName,StandardCharsets.UTF_8.toString());

            // 检查 code 参数是否为空
            if (code == null || code.trim().isEmpty()) {
                return new Result<>(HttpStatus.BAD_REQUEST.value(), "Code parameter cannot be null or empty.", null);
            }

            // 拼接请求的URL
            String url = "https://api.weixin.qq.com/sns/jscode2session?"
                    + "appid=" + appId
                    + "&secret=" + secret
                    + "&js_code=" + code
                    + "&grant_type=authorization_code";

            // 发送 HTTP 请求
            // 利用spring原生http请求工具对接口进行请求
            String jsonData = restTemplate.getForObject(url, String.class);
            // 请求到的是json数据，用fastjson
            JSONObject jsonObject = JSONObject.parseObject(jsonData);

            // 如果请求失败
            if (jsonObject.containsKey("errcode")) {
                result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
                result.setMessage(jsonObject.getString("errmsg"));
                return result;
            }

            // 获取重要数据（openid和session_key）
            String openid = jsonObject.getString("openid");
            String sessionKey = jsonObject.getString("session_key");


            // 输出日志
//            System.out.println("--------------------------------------------------------------");
//            System.out.println("openid=" + openid);
//            System.out.println("sessionKey=" + sessionKey);

            // 返回成功的结果
            result.setCode(HttpStatus.OK.value());
            result.setOpenid("privary");
            result.setSession_key("priavry");
            //result.setMessage("注册成功！");


            //先检查数据库中该用户是否已经注册
            Boolean exists = usersMapper.checkUserByOpenID(openid);
            if (exists == null || !exists){
                //没有该用户才写入数据库
                //写入数据库（携带avatarUrl,nickName,openid）
                usersMapper.addUserByOpenId(newAvatarUrl,newNickName,openid);
                result.setMessage("请点击登录按钮！");
            }else{
                //返回信息(登录)
                System.out.println("您已经注册过了！");

                //根据查询到的openid查询数据库中是否已经拥有
                //System.out.println(exists);

                //找到用户
                //如果已经有该用户，则根据openid返回用户信息
                List<Users> users= usersMapper.selectUserByOpenId(openid);
                result.setUrl(users.get(0).getUrl());
                result.setName(users.get(0).getName());
                result.setOpenid(users.get(0).getOpenid());
                result.setIdentity(users.get(0).getIdentity());
                result.setMessage("数据更新成功！");
            }

        }catch (Exception e) {
            System.out.println("Error processing register request"+e);
            result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setMessage("Internal server error.");
        }

        return result;
    }

//    改变身份
    @PostMapping("/changeIdentity")
    public Result<Object> changeIdentity(@RequestBody UserInfo userInfo){
        Result<Object> result = new Result<>();

        try {
            String openid = userInfo.getOpenId();

            Boolean exists = usersMapper.changeUserByOpenId(openid);

            if (exists){
                result.setCode(200);
                result.setMessage("修改成功！");
                return result;
            }else {
                result.setCode(500);
                result.setMessage("修改失败");
                return result;
            }
        }catch (Exception e){
            System.out.println("Error processing register request"+e);
            result.setMessage("Internal server error.");
        }

        return result;
    }

}
